﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace Technoera.Common.Interop.OleDb
{
    public class ParseEnumExportMapping<T> : ExportMappingBase
    {
        public ParseEnumExportMapping(string sourcePropertyName, string targetColumnName, Type enumType, Dictionary<T, string> enumTextValues)
            : base(targetColumnName, new SizedDataTypeDefinition(SizedDbType.UnicodeVarChar, 255))
        {
            SourcePropertyName = sourcePropertyName;
            EnumType = enumType;
            EnumTextValues = enumTextValues;
        }

        private string _sourcePropertyName;
        public string SourcePropertyName
        {
            get
            {
                if (_sourcePropertyName == null)
                    _sourcePropertyName = string.Empty;

                return _sourcePropertyName;
            }
            set
            {
                _sourcePropertyName = value;
            }
        }

        public Type EnumType { get; protected set; }

        private Dictionary<T, string> _enumTextValues;
        public Dictionary<T, string> EnumTextValues
        {
            get
            {
                if (_enumTextValues == null)
                    _enumTextValues = new Dictionary<T, string>();

                return _enumTextValues;
            }
            private set
            {
                _enumTextValues = value;
            }
        }

        #region IExportMapping Members

        public override object GetPropertyValue(object instance)
        {
            T value = default(T);
            Type sourceType = instance.GetType();
            if (SourcePropertyName.IndexOf('.') < 0)
            {
                PropertyInfo property = sourceType.GetProperty(SourcePropertyName);
                value = (T)property.GetValue(instance, null);
            }
            else
            {
                value = (T)ReflectionHelper.GetNestedPropertyValue(sourceType, SourcePropertyName, instance);
            }
            return EnumTextValues[value];
        }

        #endregion
    }
}
